//
//  JMBankAccountController.m
//  NewiOSProject
//
//  Created by JMMac on 24.12.23.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "JMBankAccountController.h"
#import "JMProductCell.h"
#import "JMProductModel.h"
#import "JMChangeMyBankController.h"
#import "JMOriginCardNumVC.h"
#import "JMPermissionHelper.h"
#import "JMSlicenseVC.h"

@interface JMBankAccountController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIView *contV;
    NSInteger type;
    NSString *bankCode;
    NSString *bankName;
    NSString *bankCard;
    
}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UIView *headerView;
@property (nonatomic, strong)UIView *emptyView;
@property (nonatomic, strong)NSString * curChannel;
@end

@implementation JMBankAccountController

- (void)viewDidLoad {
    [super viewDidLoad];
    type = 1;
    self.TitleLabel.text = @"Cuenta bancaria";
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.emptyView];
    [self getDataList];
    [self.backBtn setImage:ImageNamed(@"ICON／zuo_black") forState:(UIControlStateNormal)];

}

-(void)getDataList{
    NSDictionary *dic = @{
        
    };
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/auth/bank-card-list2") params:dic success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        NSDictionary *data = ((NSArray *)dataDic).firstObject;
        BOOL hasData = NO;
       
        if (data != nil ) {
            NSArray *productNameAndSloganList = data[@"productNameAndSloganList"];
            if (productNameAndSloganList!=nil &&[productNameAndSloganList isKindOfClass:NSArray.class]) {
                self.dataArray = [JMProductModel mj_objectArrayWithKeyValuesArray:productNameAndSloganList];
            }
            JMProjectManager.sharedJMProjectManager.loginUser.step = data[@"step"];
            
            NSString *dataStr = (NSString *)data[@"data"];
            NSData *resultData = [dataStr dataUsingEncoding:(NSUTF8StringEncoding)];
            if (resultData != nil) {
                hasData = YES;
            }
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:resultData options:(NSJSONReadingFragmentsAllowed) error:nil];
            bankCode = dataDic[@"bankCode"];
            bankName = dataDic[@"bankName"];
            bankCard = dataDic[@"bankCard"];

            [self.tableView reloadData];
            _tableView.tableHeaderView = self.headerView;

            self.emptyView.hidden = YES;
        }else{
            self.emptyView.hidden = NO;
        }
        
    } fail:^(NSString * _Nonnull errorMsg) {
        self.emptyView.hidden = NO;
    }];
    
}
//MARK: -UITableViewDataSource UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JMProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JMProductCell" forIndexPath:indexPath];
    if (indexPath.row < self.dataArray.count) {
        JMProductModel *model = self.dataArray[indexPath.row];
        model.isFold = YES;
        cell.model = model;
        cell.selectionStyle = 0;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


}

//MARK: -lazyLoad
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,NAVIGATION_BAR_HEIGHT(), kAppW(), kAppH()-NAVIGATION_BAR_HEIGHT()) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 117;
        [_tableView registerClass:[JMProductCell class] forCellReuseIdentifier:@"JMProductCell"]; // 注册UITableViewCell
        _tableView.separatorColor = UIColor.clearColor;
        _tableView.sectionHeaderTopPadding = 0;
        _tableView.backgroundColor = Hex_Str_COLOR(@"#F6F9FE");
        _tableView.tableFooterView = self.footerView;
    }
    return _tableView;
}
-(UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), ScaleW(188)+60))];
        _headerView.backgroundColor = Hex_Str_COLOR(@"#F6F9FE");
        
        UIView *bgV = [[UIView alloc]initWithFrame:(CGRectMake(24, 24, kAppW()-48, ScaleW(140)))];
        
        [bgV setShadowAndCornerWithCornerRadius:8 shadowRadius:24 shadowColor:HexAlpha_Str_COLOR(@"#B453FF", 0.34) shadowOffset:(CGSizeMake(0, 8)) shadowOpacity:1 borderWidth:2 borderColor:WhiteColor()];
        [_headerView addSubview:bgV];
        
        bgV.backgroundColor = GradientColorWithColor(bgV.size, FXGradientChangeDirectionVertical, HexAlpha_Str_COLOR(@"#3C57F8", 1), HexAlpha_Str_COLOR(@"#BB52FF", 1));

        
        UIImageView *bankIconImgV= [[UIImageView alloc]initWithFrame:(CGRectMake(24, 24, 36, 36))];
        [bgV addSubview:bankIconImgV];
        bankIconImgV.hidden = YES;
        
        UILabel *bankNameLab = [JMControl createLabelWithFrame:(CGRectMake(bankIconImgV.right+12, bankIconImgV.top, kAppW(), 24)) Font:mediumFont(17) Text:bankName color:WhiteColor()];
        [bgV addSubview:bankNameLab];
        
        
        UIButton *modifyBtn = [JMControl createButtonWithFrame:(CGRectMake(bgV.width-24-40, 24, 40, 40)) ImageName:@"xiu gai" Target:self Action:@selector(getStep) font:nil Title:nil];
        [bgV addSubview:modifyBtn];
        
        UILabel *bankNumLab = [JMControl createLabelWithFrame:(CGRectMake(0, bankNameLab.bottom+37, bgV.width, 32)) Font:mediumFont(22) Text:bankCard color:Hex_Str_COLOR(@"#ffffff")];
        bankNumLab.textAlignment = 1;
        [bgV addSubview:bankNumLab];
        
        
        
        UIView *sectionV = [[UIView alloc]initWithFrame:(CGRectMake(0, ScaleW(188), kAppW(), 60))];
        UILabel *soloLab = [JMControl createLabelWithFrame:(CGRectMake(0, 24, 150, 24)) Font:fontWithWeight(17, UIFontWeightMedium) Text:@"Productos vinculados" color:Hex_Str_COLOR(@"#222222")];
        [sectionV addSubview:soloLab];
        soloLab.backgroundColor = WhiteColor();
        soloLab.textAlignment = 1;
        soloLab.centerX = kAppW()/2;
        
        UIView *lineV = [[UIView alloc]initWithFrame:(CGRectMake(0, 0, 198, 2))];
        lineV.backgroundColor = Hex_Str_COLOR(@"#3C57F8");
        [sectionV addSubview:lineV];
        [sectionV sendSubviewToBack:lineV];
        lineV.center = soloLab.center;
        CGFloat w = CalculateLabelWidthWithLab(soloLab)+16;
        soloLab.width = w;
        soloLab.centerX = kAppW()/2;
        lineV.width = w+16+48;
        lineV.centerX = soloLab.centerX;
        
        [_headerView addSubview:sectionV];
        sectionV.backgroundColor = WhiteColor();
    }
    return _headerView;
}
-(void)modifyBtnClick{
    JMChangeMyBankController *vc = JMChangeMyBankController.new;
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)getStep{
    [JMBaseRequest.sharedInstance requestBasePost:BasePostRequestUrl(@"/api/auth/get-modify_steps") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        NSArray *dataArr = [dataDic safeArrayForKey:@"step"];
        if([dataArr isKindOfClass:NSArray.class]&&dataArr.count){
            if(dataArr.count==2){//如果两个都包含则先做银行卡校验，银行卡校验成功再做活体校验
                JMOriginCardNumVC*vc = JMOriginCardNumVC.new;
                vc.step = @"check_origin&liveness";
                [self.navigationController pushViewController:vc animated:YES];
            }else {
                if([dataArr.firstObject isEqualToString:@"check_origin"]){//原银行卡交验
                    //2.1验证原银行卡
                    JMOriginCardNumVC*vc = JMOriginCardNumVC.new;
                    vc.step = @"check_origin";
                    [self.navigationController pushViewController:vc animated:YES];
                }else{//需要做活体校验
                    [[JMPermissionHelper sharedInstance] accessCamera:^(BOOL granted) {//先检查相机权限，再检测活体授权
                        if (granted) {
                            [self getLiveConfig];
                        }
                    }];
                }
            }
        }else{
            JMOriginCardNumVC*vc = JMOriginCardNumVC.new;
            vc.step = @"check_origin&liveness";
            [self.navigationController pushViewController:vc animated:YES];
        }
    } fail:^(NSString * _Nonnull errorMsg) {
        
    }];
}
//2.2获取活体渠道 检查是否需要活体检验
-(void)getLiveConfig{
    [[JMBaseRequest sharedInstance]  requestBasePost:BasePostRequestUrl(@"/api/auth/livenConfig") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        
        NSNumber * isSkip =dataDic[@"skipLiven"];
        if(isSkip.intValue){
            [self stopAnimating];
            [self modifyBtnClick];
        }else{
            //2.检查用户是否可以做某项授权接口
            self.curChannel = dataDic[@"livenChannel"];

            [self checkAuthResultWithChannelWith:self.curChannel];
        }
    } fail:^(NSString * _Nonnull errorMsg) {
        [self stopAnimating];
        [self showMessage:errorMsg];
    }];
    
}
//3.检测用户是否可以进行认证（在首页进入时 如果获取的步骤是第三步，就要直接调用该接口，失败直接谈提示框，并不能进入认证）
-(void)checkAuthResultWithChannelWith:(NSString *)livenChannel{
    
    [[JMBaseRequest sharedInstance]  requestBasePost:BasePostRequestUrl(@"/api/auth/check") params:@{@"authType":@"LIVENESS"} success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        BOOL checkout = dataDic[@"checkResult"];
        [self stopAnimating];
        if(checkout){
            [self showSlicenseLivenessSDK];
            return;
            if([livenChannel isEqualToString:@"SILENCE_LIVENESS"]){//静默活体（按新增的UI来做就行）
                [self stopAnimating];
                [self showSlicenseLivenessSDK];
            } else if([livenChannel isEqualToString:@"CLOUDUN"]){//Cloudn活体
                [self stopAnimating];
//                LNDetectViewController *vc = [[LNDetectViewController alloc] initWithNibName:@"LNDetectViewController" bundle:nil];
//                vc.userID = JMProjectManager.sharedJMProjectManager.loginUser.userId;//TODO
//                vc.delegate = self;
//                [self.navigationController pushViewController:vc animated:NO];
            } else{//Advance
//                [self getLicense];
            }
        }else{
            [self showMessage:@"Lo sentimos. Aún no es la fecha del evento"];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } fail:^(NSString * _Nonnull errorMsg) {
        [self stopAnimating];
    }];
}
-(void)showSlicenseLivenessSDK{
    JMSlicenseVC *vc = JMSlicenseVC.new;
    vc.type=2;
    [self.navigationController pushViewController:vc animated:YES];
}
-(UIView *)emptyView{
    if (!_emptyView) {
        _emptyView = [[UIView alloc]initWithFrame:(CGRectMake(0, _tableView.top, kAppH(),self.tableView.height))];
        _emptyView.backgroundColor = Hex_Str_COLOR(@"#F7F7F5");
        UIImageView *imgV = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 0, 140, 140))];
        [imgV setImage:ImageNamed(@"空的")];
        [_emptyView addSubview:imgV];;
        imgV.center = CGPointMake(kAppW()/2, _emptyView.height/2);
        UILabel *lab = [JMControl createLabelWithFrame:(CGRectMake(0, imgV.bottom+25, kAppW(), FontH(18))) Font:Font(15) Text:@"Está vacío ahora, vuelva más tarde" color:Hex_Str_COLOR(@"#3C57F8")];
        [_emptyView addSubview:lab];
        lab.textAlignment  = 1;
        
        UIButton *delegateBtn = [JMControl createButtonWithFrame:(CGRectMake(0, _emptyView.height-67, kAppW(), 37)) Target:self Action:@selector(delegateBtnClick) Title:@"《 Politica de privacidad 》" titlColor:Hex_Str_COLOR(@"#222222") font:Font(12) tag:1 backgroundColor:UIColor.clearColor];
        [_emptyView addSubview:delegateBtn];
    }
    return _emptyView;
}
@end
